package com.wisdom.smartbook.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.wisdom.smartbook.R;
import com.wisdom.smartbook.app.MyApp;
import com.wisdom.smartbook.listener.CameraPreviewListener;
import com.wisdom.smartbook.listener.OnDownloadListener;
import com.wisdom.smartbook.permission.PermissionUtils;
import com.wisdom.smartbook.utils.AndJSBridge;
import com.wisdom.smartbook.utils.AndroidtoJs;
import com.wisdom.smartbook.utils.DeviceUtil;
import com.wisdom.smartbook.utils.DialogTipsUtil;
import com.wisdom.smartbook.utils.DialogUtil;
import com.wisdom.smartbook.utils.DownloadUtil;
import com.wisdom.smartbook.utils.FileManager;
import com.wisdom.smartbook.utils.FileTool;
import com.wisdom.smartbook.utils.IntentUtil;
import com.wisdom.smartbook.utils.KLog;
import com.wisdom.smartbook.utils.NetworkUtil;
import com.wisdom.smartbook.utils.SystemUtil;
import com.wisdom.smartbook.utils.ToastUtils;
import com.wisdom.smartbook.utils.camera.FaceUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;


/**
 * 主页
 */
public class MainActivity extends FaceRecognizeActivityNew implements AndJSBridge, CameraPreviewListener {


    //  学生端正式
    public String base_url_student_official = "https://wisdomebook.com/student/#/";
    //     教师端正式：
    public String base_url_teacher_official = "https://sjcloudview.wisdomin.cn/onlinePreview?url=aHR0cHM6Ly9vc3N2Mi53aXNkb21pbi5jbi9yZXNvdXItbWFuYWdlL1JFU09VUl9DT1VSU0VXQVJFX0ZJTEUvMjAyNDAyLzI3LzAwMDAxLzM3Njg4XzE1XzE3MDkwMTQwNzMzMzIuZG9jeA%3D%3D";
    //    public String base_url_teacher_official = "https://wisdomebook.com/teacher/#/";
    //学生
    public String base_url_student_test = "http://47.99.60.196/student/";
    //    public String base_url_student_test = "https://zs.wisdomin.cn/student/#/";
    //教师
    public String base_url_teacher_test = "http://47.99.60.196/teacher/";
//    public String base_url_teacher_test = "https://zs.wisdomin.cn/teacher/#/";


    //网络状态监听广播
    private NetWorkReceiver netWorkReceiver;

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;
    private final static int REQUEST_CROP_CODE = 10002;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//        }
        registerReceiver();
    }


//    @Override
//    public void onConfigurationChanged(@NonNull @NotNull Configuration newConfig) {
//        super.onConfigurationChanged(newConfig);
//
//            if (MainActivity.this.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { // 现在的方向是横屏显示
//                Toast.makeText(MainActivity.this, "已改变为竖屏方向",Toast.LENGTH_SHORT).show();
//                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 变为竖屏显示
//            } else if (MainActivity.this.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { // 如果为竖屏显示
//                Toast.makeText(MainActivity.this, "已改变为横屏方向", Toast.LENGTH_SHORT).show();
//                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 变为横屏显示
//            }
//
//    }

    protected void initView() {
        super.initView();
        initWebView();
        DeviceUtil.printDeviceInfo();
    }

    @Override
    protected void initData() {
        super.initData();
        setWeb();
        DialogUtil.showProgressDialog(this, "正在加载...");
//        loadUrl();
    }

    private void loadUrl() {
        if (getApplicationInfo().processName.endsWith("test")) {
            if (getApplicationInfo().processName.contains("student")) {
                mWebView.loadUrl(base_url_student_test);
            } else {
                mWebView.loadUrl(base_url_teacher_test);
            }
        } else {
            if (getApplicationInfo().processName.contains("student")) {
                mWebView.loadUrl(base_url_student_official);
            } else {
                mWebView.loadUrl(base_url_teacher_official);
            }
        }

    }

    private void setWeb() {
        try {
            if (Build.VERSION.SDK_INT >= 16) {
                Class<?> clazz = mWebView.getSettings().getClass();
                Method method = clazz.getMethod(
                        "setAllowUniversalAccessFromFileURLs", boolean.class);//利用反射机制去修改设置对象
                if (method != null) {
                    method.invoke(mWebView.getSettings(), true);//修改设置
                }
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private void initWebView() {

        //开启webView硬件加速
        this.mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        final WebSettings webSetting = mWebView.getSettings();
        webSetting.setAllowUniversalAccessFromFileURLs(true);
        webSetting.setAllowFileAccessFromFileURLs(true);

        webSetting.setAllowFileAccess(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setBlockNetworkImage(true);
        webSetting.setNeedInitialFocus(false);
        //自适应屏幕
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.setDrawingCacheEnabled(true);
        webSetting.setLoadWithOverviewMode(true);
        mWebView.addJavascriptInterface(new AndroidtoJs(this), "AndroidJs");
//        //修改相应设置即可
        webSetting.setMediaPlaybackRequiresUserGesture(false);
        webSetting.setAppCachePath(mActivity.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(mActivity.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(mActivity.getDir("geolocation", 0)
                .getPath());
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        long time = System.currentTimeMillis();
        removeSearchBoxImpl();
        CookieSyncManager.createInstance(mActivity);
        CookieSyncManager.getInstance().sync();
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                webSetting.setBlockNetworkImage(false);
                mWebView.setVisibility(View.VISIBLE);
                DialogUtil.closeProgressDialog();


            }

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
                DialogUtil.showProgressDialog(mContext, "正在加载中...");
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView webView, String s) {
                KLog.d("shouldInterceptRequest", s);
                return super.shouldInterceptRequest(webView, s);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                KLog.d("shouldOverrideUrlLoading", url);
                if (url.contains("https://beian.miit.gov.cn")) {
                    return false;
                }
                if (!url.startsWith("https://zs.wisdomin.cn") && !url.startsWith("https://wisdomebook.com") && !url.startsWith("http://47.99.60.196")) {
                    if (url.contains("/video/")) {
                        Intent intent = new Intent(mActivity, VideoActivity.class);
                        intent.putExtra("urlStr", url);
                        startActivity(intent);
                    } else if (url.contains("/pdf/")) {
                        Intent intent = new Intent(mActivity, FileBrowserActivity.class);
                        intent.putExtra("urlStr", url);
                        startActivity(intent);
                    } else if (url.contains("/file/")) {
                        Intent intent = new Intent(mActivity, FileBrowserActivity.class);
                        intent.putExtra("urlStr", url);
                        startActivity(intent);
                    }
                    return false;
                }
                return true;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
                KLog.e("shouldOverrideUrlLoading2", webResourceRequest.getUrl().toString());
                return super.shouldOverrideUrlLoading(webView, webResourceRequest);
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, com.tencent.smtt.export.external.interfaces.SslError sslError) {
//                super.onReceivedSslError(webView, sslErrorHandler, sslError);
                sslErrorHandler.proceed();
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                KLog.d(i, s, s);
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {

                                        @Override
                                        public void onProgressChanged(WebView view, int newProgress) {
                                            super.onProgressChanged(view, newProgress);
                                            KLog.e("加载进度", newProgress + "");
                                        }

                                        @Override
                                        public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
                                            return false;
                                        }


                                        //For Android  >= 4.1
                                        @Override
                                        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                                            uploadMessage = valueCallback;
                                            openImageChooserActivity();
                                        }

                                        // For Android >= 5.0
                                        @Override
                                        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                                            uploadMessageAboveL = filePathCallback;
                                            openImageChooserActivity();
                                            return true;
                                        }

                                    }
        );
    }

    // 2.回调方法触发本地选择文件
    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
//        i.setType("image/*");//图片上传
//        i.setType("file/*");//文件上传
        i.setType("*/*");//文件上传
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    @Override
    protected void onPause() {
        mWebView.onPause();
        mWebView.pauseTimers();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mWebView.onResume();
        mWebView.resumeTimers();
        super.onResume();


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterReceiver();
        //销毁
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeSessionCookies(null);
        cookieManager.removeAllCookie();
        cookieManager.flush();
        mRootView.removeAllViews();
        if (mWebView != null) {
            mWebView.clearCache(false);
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }

    }

    private boolean removeSearchBoxImpl() {
        if (hasHoneycomb() && !hasJellyBeanMR1()) {
            mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
            mWebView.removeJavascriptInterface("accessibility");
            mWebView.removeJavascriptInterface("accessibilityTraversal");
            return true;
        }
        return false;
    }

    private boolean hasHoneycomb() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }

    private boolean hasJellyBeanMR1() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
    }


    /**
     * 设置点击返回按钮，跳转到上一个html页面，而不是退出当前activity
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    ToastUtils.showShort("再按一次退出");
                    exitTime = System.currentTimeMillis();
                } else {
                    finish();
                    System.exit(0);
                }
            }
            return true;

        }
        return super.onKeyDown(keyCode, event);
    }

    private long exitTime = 0;


    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }

    @Override
    public void openLogin() {
        PermissionUtils.getInstance().checkPermissionsCamera(mActivity, new PermissionUtils.onPermissionsResultListener() {
            @Override
            public void onPermissionGranted() {
                MyApp.getInstance().setIsLoginSuccess(false);
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setCameraPreviewListener(MainActivity.this::onPreview);
                        setFaceRecog();
                    }
                });
            }

            @Override
            public void onPermissionDenied(List<String> permissionList, String permissionsHint) {
                ToastUtils.showShortSafe("未获取到所需的相机权限，此功能暂不能使用！");
            }
        });


    }

    @Override
    public void loginTip(int code, String tip) {
        ToastUtils.showShortSafe(tip);

    }

    @Override
    public void logout() {

    }

    /**
     * 打开相机
     */
    @Override
    public void openCamera() {
        selectOnclick();
    }

    @Override
    public void appUpdate(int upgradeId, String updateInfo) {

    }

    @Override
    public void loginSuccess() {
        MyApp.getInstance().setIsLoginSuccess(true);
        mHandler.removeCallbacks(mRunnable);
        mNV21Bytes = null;
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTtcVideoView.setVisibility(View.GONE);
            }
        });
        release();
        KLog.d("登录成功！");


    }

    String fileUrl;

    @Override
    public void downloadFile(String fileName, String fileUrl, String format) {
        this.fileUrl = fileUrl;
        if (format.equals("mp4")) {
            Intent intent = new Intent(mActivity, VideoActivity.class);
            intent.putExtra("urlStr", fileUrl);
            startActivity(intent);
            return;
        }
        DialogUtil.showProgressDialog(mActivity, getResources().getString(R.string.download_ing));
        //储存下载文件的目录
        DownloadUtil.get().download(fileUrl, FileManager.getFileCachePath(mActivity), fileName,
                new OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file, boolean isNew) {
                        //下载完成进行相关逻辑操作
                        Message msg = mHandler.obtainMessage();
                        if (format.equals("png") || format.equals("jpg")) {
                            msg.what = 11;
                        } else {
                            if (isNew) {
                                msg.what = 10;
                            } else {
                                msg.what = 13;
                            }
                        }
                        msg.obj = file.getAbsolutePath();
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onDownloading(int progress) {
//                        Message msg = mHandler.obtainMessage();
//                        msg.what = 11;
//                        msg.obj = progress;
//                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onDownloadFailed(Exception e) {
                        //下载异常进行相关提示操作
                        Message msg = mHandler.obtainMessage();
                        msg.what = 12;
                        msg.obj = e;
                        mHandler.sendMessage(msg);
                    }
                });
//
//        Intent intent = new Intent(mActivity, FileBrowserActivity.class);
//        intent.putExtra("urlStr", fileUrl);
//        startActivity(intent);
    }

    /**
     * decoderBase64File:(将base64字符解码保存文件). <br/>
     *
     * @param base64Code 编码后的字串
     * @param savePath   文件保存路径
     * @throws Exception
     * @author guhaizhou@126.com
     * @since JDK 1.6
     */
    public void decoderBase64File(String base64Code, String savePath) throws Exception {
        byte[] buffer = Base64.decode(base64Code, Base64.DEFAULT);
        FileOutputStream out = new FileOutputStream(savePath);
        out.write(buffer);
        out.flush();
        out.close();
    }


    private long timePre = 0;

    @Override
    public void onPreview(byte[] nv21, int width, int height) {
        if (System.currentTimeMillis() - timePre > 1000) {
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    timePre = System.currentTimeMillis();
                    if (mNV21Bytes == null || mNV21Bytes.length == 0) {
                        return;
                    }
                    Bitmap bitmap = FaceUtils.getBitmapImageFromYUV(mNV21Bytes, previewSize.width, previewSize.height);
                    if (bitmap != null) {
                        String base64Str = FaceUtils.bitmap2base64(bitmap);
                        String script = String.format("javascript:getFaceFun('" + base64Str + "')");
                        mWebView.evaluateJavascript(script, new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {
                                KLog.d("上传成功 。。。");
                            }
                        });
                    }
                }
            });
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            DialogUtil.closeProgressDialog();
            if (msg.what == 10) {
                String filePath = (String) msg.obj;
                DialogTipsUtil.openFileDialog(mActivity, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (filePath.endsWith(".pdf")) {
                            Intent intent = new Intent(mActivity, PdfViewActivity.class);
                            intent.putExtra("filePath", filePath);
                            startActivity(intent);
                        } else {
                            try {
                                startActivityForResult(IntentUtil.getExcelFileIntent(mActivity, filePath), 10);
                            } catch (Exception e) {
                                e.printStackTrace();
                                ToastUtils.showLongSafe("设备暂不支持文件浏览服务");
                            }
                        }
                    }
                });
            } else if (msg.what == 11) {
                String filePath = (String) msg.obj;
                FileManager.saveBitmap(mActivity, filePath);
                FileManager.deleteFile(filePath);
                ToastUtils.showLong("文件已保存到相册");
            } else if (msg.what == 12) {
                ToastUtils.showLong("文件保存失败！");
            } else if (msg.what == 13) {
                String filePath = (String) msg.obj;
                if (filePath.endsWith(".pdf")) {
                    Intent intent = new Intent(mActivity, PdfViewActivity.class);
                    intent.putExtra("filePath", filePath);
                    startActivity(intent);
                } else {
                    try {
                        startActivityForResult(IntentUtil.getExcelFileIntent(mActivity, filePath), 10);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showLongSafe("设备暂不支持文件浏览服务");

                    }
                }
            } else if (msg.what == 14) {
                loadUrl();
            }

        }
    };


    //注册网络的广播
    private void registerReceiver() {
        IntentFilter filterNet = new IntentFilter();
        filterNet.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        netWorkReceiver = new NetWorkReceiver();
        registerReceiver(netWorkReceiver, filterNet);

    }

    //注销网络的广播
    private void unRegisterReceiver() {
        if (netWorkReceiver != null) {
            unregisterReceiver(netWorkReceiver);
        }
    }

    class NetWorkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                KLog.d("NetWorkReceiver");
                if (NetworkUtil.isNetworkAvailable(context) && NetworkUtil.isConnected(context)) {
                    KLog.d("网络已连接，刷新主页");
                    mHandler.sendEmptyMessage(14);
                } else {
                    KLog.d("网络已断开");
                }
            }
        }
    }


    // 3.选择图片后处理
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            // Uri result = (((data == null) || (resultCode != RESULT_OK)) ? null : data.getData());
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
        if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
            Log.d("aaa", "data != null" + (data != null));
            if (null != imageFilePath && imageFilePath.length() > 0) {
                cropImage(FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileProvider",
                        new File(imageFilePath)));
            }
        } else if (requestCode == REQUEST_CROP_CODE && resultCode == RESULT_OK) {
            Bitmap bitmap = BitmapFactory.decodeFile(cropPicPath);
            if (bitmap == null) {
                String script = String.format("javascript:getPhotos('" + "')");
                mWebView.evaluateJavascript(script, new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        KLog.d("上传成功 。。。");
                        try {
                            FileManager.deleteFile(imageFilePath);
                            FileManager.deleteFile(cropPicPath);
                        } catch (Exception e) {
                            KLog.d(e.getLocalizedMessage());
                        }

                    }
                });
            } else {
                int degree = readPictureDegree(cropPicPath);
                Bitmap bitmapDegree = rotaingImageView(degree, bitmap);
                saveBitmapFileToFile(bitmapDegree, "");
                //存放缩略图
                String compressFilePath = FileManager.getImageCachePath(mContext) + File.separator + System.currentTimeMillis() + ".jpg";
                FileTool.compress(BitmapFactory.decodeFile(cropPicPath), compressFilePath);
                Bitmap bitmap2 = BitmapFactory.decodeFile(compressFilePath);
                String base64Str = FaceUtils.bitmap2base64(bitmap2);
                String script = String.format("javascript:getPhotos('" + base64Str + "')");
                mWebView.evaluateJavascript(script, new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        KLog.d("上传成功 。。。");
                        try {
                            FileManager.deleteFile(imageFilePath);
                            FileManager.deleteFile(cropPicPath);
                            FileManager.deleteFile(compressFilePath);
                        } catch (Exception e) {
                            KLog.d(e.getLocalizedMessage());
                        }

                    }
                });
            }
        } else {
            //这里uploadMessage跟uploadMessageAboveL在不同系统版本下分别持有了
            //WebView对象，在用户取消文件选择器的情况下，需给onReceiveValue传null返回值
            //否则WebView在未收到返回值的情况下，无法进行任何操作，文件选择器会失效
            if (uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            } else if (uploadMessageAboveL != null) {
                uploadMessageAboveL.onReceiveValue(null);
                uploadMessageAboveL = null;
            }
        }
    }

    String cropPicPath;

    private void cropImage(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        // Android 7.0需要临时添加读取Url的权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        intent.setDataAndType(uri, "image/*");
        // 使图片处于可裁剪状态
        intent.putExtra("crop", "true");
        // 裁剪框的比例（根据需要显示的图片比例进行设置）
//        if (Build.MANUFACTURER.contains("HUAWEI")) {
//            //硬件厂商为华为的，默认是圆形裁剪框，这里让它无法成圆形
//            intent.putExtra("aspectX", 9999)
//            intent.putExtra("aspectY", 9998)
//        } else {
//            //其他手机一般默认为方形
//            intent.putExtra("aspectX", 1)
//            intent.putExtra("aspectY", 1)
//        }

        // 设置裁剪区域的形状，默认为矩形，也可设置为圆形，可能无效
        // intent.putExtra("circleCrop", true);
        // 让裁剪框支持缩放
        intent.putExtra("scale", true);
        // 属性控制裁剪完毕，保存的图片的大小格式。太大会OOM（return-data）
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 400);

        // 生成临时文件
        File cropFile = new File(FileManager.getImageCachePath(mContext) + File.separator + System.currentTimeMillis() + ".jpg");
        // 裁切图片时不能使用provider的uri，否则无法保存
//        val cropUri = getUriForFile(cropFile)
        Uri cropUri = Uri.fromFile(cropFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
        // 记录临时位置
        cropPicPath = cropFile.getAbsolutePath();

        // 设置图片的输出格式
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        // return-data=true传递的为缩略图，小米手机默认传递大图， Android 11以上设置为true会闪退
        intent.putExtra("return-data", false);

        startActivityForResult(intent, REQUEST_CROP_CODE);
    }


    // 4. 选择内容回调到Html页面
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }
}
